<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI角色扮演聊天 - 简化版</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            color: white;
            padding: 20px;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
        }
        
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        
        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .role-selection {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .role-card {
            background: rgba(255, 255, 255, 0.15);
            border-radius: 15px;
            padding: 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .role-card:hover {
            transform: translateY(-5px);
            background: rgba(255, 255, 255, 0.25);
        }
        
        .role-avatar {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.5rem;
            font-weight: bold;
            margin: 0 auto 15px;
        }
        
        .role-card h3 {
            font-size: 1.2rem;
            margin-bottom: 8px;
        }
        
        .role-card p {
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .chat-interface {
            display: none;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            padding: 20px;
            backdrop-filter: blur(10px);
        }
        
        .chat-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.2);
        }
        
        .back-btn {
            background: rgba(255, 255, 255, 0.2);
            border: none;
            color: white;
            padding: 8px 16px;
            border-radius: 15px;
            cursor: pointer;
        }
        
        .current-role {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .current-role .role-avatar {
            width: 40px;
            height: 40px;
            font-size: 1rem;
        }
        
        .messages {
            max-height: 400px;
            overflow-y: auto;
            margin-bottom: 20px;
            padding: 15px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 15px;
        }
        
        .message {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }
        
        .message.user {
            flex-direction: row-reverse;
        }
        
        .message-avatar {
            width: 35px;
            height: 35px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.2);
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }
        
        .message.user .message-avatar {
            background: linear-gradient(45deg, #4ecdc4, #44a08d);
        }
        
        .message.assistant .message-avatar {
            background: linear-gradient(45deg, #ff6b6b, #ee5a24);
        }
        
        .message-content {
            background: rgba(255, 255, 255, 0.15);
            padding: 12px 16px;
            border-radius: 15px;
            max-width: 70%;
            line-height: 1.4;
        }
        
        .message.user .message-content {
            background: rgba(78, 205, 196, 0.3);
        }
        
        .input-container {
            display: flex;
            gap: 10px;
            align-items: flex-end;
        }
        
        .input-box {
            flex: 1;
            display: flex;
            align-items: flex-end;
            gap: 10px;
            background: rgba(255, 255, 255, 0.15);
            border-radius: 20px;
            padding: 12px 16px;
        }
        
        .input-box textarea {
            flex: 1;
            background: none;
            border: none;
            outline: none;
            color: white;
            font-size: 14px;
            resize: none;
            max-height: 80px;
        }
        
        .input-box textarea::placeholder {
            color: rgba(255, 255, 255, 0.7);
        }
        
        .voice-control-btn, .send-btn {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .voice-control-btn {
            background: rgba(255, 255, 255, 0.2);
            color: white;
        }
        
        .voice-control-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.05);
        }
        
        .voice-control-btn.speaking {
            background: #ff6b6b;
            animation: pulse 1.5s infinite;
        }
        
        .send-btn {
            background: linear-gradient(45deg, #4ecdc4, #44a08d);
            color: white;
        }
        
        .send-btn:hover {
            transform: scale(1.05);
        }
        
        @keyframes pulse {
            0% { box-shadow: 0 0 0 0 rgba(255, 107, 107, 0.7); }
            70% { box-shadow: 0 0 0 10px rgba(255, 107, 107, 0); }
            100% { box-shadow: 0 0 0 0 rgba(255, 107, 107, 0); }
        }
        
        .loading {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        
        .loading span {
            width: 6px;
            height: 6px;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.7);
            animation: typing 1.4s infinite ease-in-out;
        }
        
        .loading span:nth-child(2) { animation-delay: 0.2s; }
        .loading span:nth-child(3) { animation-delay: 0.4s; }
        
        @keyframes typing {
            0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
            40% { transform: scale(1); opacity: 1; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎭 AI角色扮演聊天</h1>
            <p>选择角色开始对话</p>
        </div>
        
        <div id="role-selection">
            <div class="role-selection">
                <div class="role-card" onclick="selectRole('socrates')">
                    <div class="role-avatar">苏</div>
                    <h3>苏格拉底</h3>
                    <p>古希腊哲学家</p>
                </div>
                <div class="role-card" onclick="selectRole('harry_potter')">
                    <div class="role-avatar">哈</div>
                    <h3>哈利·波特</h3>
                    <p>魔法世界救世主</p>
                </div>
                <div class="role-card" onclick="selectRole('shakespeare')">
                    <div class="role-avatar">莎</div>
                    <h3>莎士比亚</h3>
                    <p>文学巨匠</p>
                </div>
                <div class="role-card" onclick="selectRole('einstein')">
                    <div class="role-avatar">爱</div>
                    <h3>爱因斯坦</h3>
                    <p>理论物理学家</p>
                </div>
            </div>
        </div>
        
        <div id="chat-interface" class="chat-interface">
            <div class="chat-header">
                <button class="back-btn" onclick="showRoleSelection()">← 返回</button>
                <div class="current-role">
                    <div class="role-avatar" id="currentRoleAvatar">苏</div>
                    <div>
                        <h3 id="currentRoleName">苏格拉底</h3>
                    </div>
                </div>
            </div>
            
            <div class="messages" id="messages">
                <!-- 消息将在这里显示 -->
            </div>
            
            <div class="input-container">
                <div class="input-box">
                    <textarea id="messageInput" placeholder="输入消息..." rows="1"></textarea>
                    <button class="voice-control-btn" id="voiceControlBtn" onclick="toggleVoice()" title="停止语音">🔇</button>
                    <button class="send-btn" onclick="sendMessage()">📤</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        let currentRole = null;
        let conversationId = null;

        // 角色数据
        const roles = {
            'socrates': { name: '苏格拉底', description: '古希腊哲学家' },
            'harry_potter': { name: '哈利·波特', description: '魔法世界救世主' },
            'shakespeare': { name: '莎士比亚', description: '文学巨匠' },
            'einstein': { name: '爱因斯坦', description: '理论物理学家' }
        };

        // 选择角色
        function selectRole(roleId) {
            console.log('选择角色:', roleId);
            currentRole = { id: roleId, ...roles[roleId] };
            
            // 更新界面
            document.getElementById('currentRoleAvatar').textContent = currentRole.name.charAt(0);
            document.getElementById('currentRoleName').textContent = currentRole.name;
            
            // 切换界面
            document.getElementById('role-selection').style.display = 'none';
            document.getElementById('chat-interface').style.display = 'block';
            
            // 清空消息并添加欢迎消息
            document.getElementById('messages').innerHTML = '';
            conversationId = null;
            addMessage('assistant', `你好！我是${currentRole.name}，很高兴与你对话！`);
        }

        // 显示角色选择
        function showRoleSelection() {
            document.getElementById('role-selection').style.display = 'block';
            document.getElementById('chat-interface').style.display = 'none';
        }

        // 发送消息
        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const message = input.value.trim();
            if (!message || !currentRole) return;

            // 停止当前语音播放
            stopCurrentSpeech();

            // 添加用户消息
            addMessage('user', message);
            input.value = '';

            // 显示加载状态
            const loadingId = addLoadingMessage();

            try {
                const response = await fetch('/api/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        roleId: currentRole.id,
                        message: message,
                        conversationId: conversationId
                    })
                });

                const data = await response.json();
                
                // 移除加载状态
                removeMessage(loadingId);
                
                if (response.ok) {
                    // 添加AI回复
                    addMessage('assistant', data.response);
                    conversationId = data.conversationId;
                    
                    // 语音播放新回复
                    speakText(data.response);
                } else {
                    addMessage('assistant', '抱歉，我现在无法回复。请稍后再试。');
                }
            } catch (error) {
                console.error('发送消息失败:', error);
                removeMessage(loadingId);
                addMessage('assistant', '网络错误，请检查连接后重试。');
            }
        }

        // 添加消息
        function addMessage(role, content) {
            const messagesContainer = document.getElementById('messages');
            const messageId = 'msg_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
            
            const messageElement = document.createElement('div');
            messageElement.className = `message ${role}`;
            messageElement.id = messageId;
            
            const avatar = role === 'user' ? '👤' : '🤖';
            messageElement.innerHTML = `
                <div class="message-avatar">${avatar}</div>
                <div class="message-content">${content}</div>
            `;
            
            messagesContainer.appendChild(messageElement);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            
            return messageId;
        }

        // 添加加载消息
        function addLoadingMessage() {
            const messagesContainer = document.getElementById('messages');
            const messageId = 'loading_' + Date.now();
            
            const messageElement = document.createElement('div');
            messageElement.className = 'message assistant';
            messageElement.id = messageId;
            
            messageElement.innerHTML = `
                <div class="message-avatar">🤖</div>
                <div class="message-content">
                    <div class="loading">
                        <span></span>
                        <span></span>
                        <span></span>
                    </div>
                </div>
            `;
            
            messagesContainer.appendChild(messageElement);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            
            return messageId;
        }

        // 移除消息
        function removeMessage(messageId) {
            const messageElement = document.getElementById(messageId);
            if (messageElement) {
                messageElement.remove();
            }
        }

        // 语音控制变量
        let currentSpeech = null;
        let isSpeaking = false;

        // 停止当前语音播放
        function stopCurrentSpeech() {
            if (isSpeaking && currentSpeech) {
                speechSynthesis.cancel();
                isSpeaking = false;
                currentSpeech = null;
                console.log('语音播放已停止');
            }
        }

        // 语音播放文本
        function speakText(text) {
            // 停止之前的语音
            stopCurrentSpeech();
            
            if ('speechSynthesis' in window) {
                const utterance = new SpeechSynthesisUtterance(text);
                utterance.lang = 'zh-CN';
                utterance.rate = 0.9;
                utterance.pitch = 1;
                utterance.volume = 0.8;
                
                // 语音开始事件
                utterance.onstart = function() {
                    isSpeaking = true;
                    currentSpeech = utterance;
                    updateVoiceButton();
                    console.log('开始语音播放:', text.substring(0, 50) + '...');
                };
                
                // 语音结束事件
                utterance.onend = function() {
                    isSpeaking = false;
                    currentSpeech = null;
                    updateVoiceButton();
                    console.log('语音播放结束');
                };
                
                // 语音错误事件
                utterance.onerror = function(event) {
                    isSpeaking = false;
                    currentSpeech = null;
                    updateVoiceButton();
                    console.error('语音播放错误:', event.error);
                };
                
                speechSynthesis.speak(utterance);
            } else {
                console.log('浏览器不支持语音合成');
            }
        }

        // 切换语音播放/停止
        function toggleVoice() {
            if (isSpeaking) {
                stopCurrentSpeech();
                updateVoiceButton();
            } else {
                // 如果没有在播放，可以重新播放最后一条AI消息
                const messages = document.querySelectorAll('.message.assistant .message-content');
                if (messages.length > 0) {
                    const lastMessage = messages[messages.length - 1].textContent;
                    speakText(lastMessage);
                }
            }
        }

        // 更新语音按钮状态
        function updateVoiceButton() {
            const voiceBtn = document.getElementById('voiceControlBtn');
            if (isSpeaking) {
                voiceBtn.textContent = '🔊';
                voiceBtn.title = '停止语音播放';
                voiceBtn.classList.add('speaking');
            } else {
                voiceBtn.textContent = '🔇';
                voiceBtn.title = '播放最后一条消息';
                voiceBtn.classList.remove('speaking');
            }
        }

        // 回车发送消息
        document.getElementById('messageInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    </script>
</body>
</html>
